package com.hxx.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hxx.domain.TUser;
import com.hxx.service.UserService;
import com.hxx.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("*.do")
public class HxxServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //获取前端的json数据
        String line = request.getReader().readLine();
        String flag = "";
        int pageNo = 1;
        int pageSize = 3;
        //判断
        if (line!=null){
            JSONObject jsonObject = JSON.parseObject(line);
            pageNo = jsonObject.getIntValue("page1");
            pageSize = jsonObject.getIntValue("size1");
            flag = jsonObject.getString("flag");
            //根据flag的值来判断是添加还是删除
            if ("delete".equals(flag)){
                String id = jsonObject.getString("id");
                userService.deleteUser(Integer.parseInt(id));
            }
            //保存
            if ("add".equals(flag)){
                TUser tUser = JSON.parseObject(line, TUser.class);
                userService.saveUser(tUser);
                return;
            }
            //更新
            if ("update".equals(flag)){
                TUser tUser = JSON.parseObject(line, TUser.class);
                userService.updateUser(tUser);
                return;
            }
        }

        //获取数据
        //List<TUser> list = userService.findAll();
        List<TUser> list = userService.findByPage(pageNo, pageSize);
        int totalCount = userService.getTotalCount();
        //创建map
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("totalCount", totalCount);
        //json转换
        String json = JSON.toJSONString(map);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
    }
}
